package com.mycat.redis.pool.single;

import com.mycat.redis.pool.JedisConnection;
import com.mycat.redis.pool.RedisConfigHelper;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 单点模式连接池
 *
 * @author roger.
 * @email 190642964@qq.com
 * @create 2016-12-20
 */
public class RedisSinglePool extends JedisConnection{

    private static JedisPool jedisPool;

    private RedisSinglePool(){
        initPool();
        System.out.println("初始化...........RedisSinglePool");
    }

    @Override
    public Jedis getResource() {
        return jedisPool.getResource();
    }

    @Override
    public void closeResource(Jedis jedis) {
        if(null != jedis){
            jedis.close();
        }
    }

    @Override
    public void initPool() {
        if(null != jedisPool){
            jedisPool.close();
            jedisPool.destroy();
        }
        if ((null != RedisConfigHelper.getPassword() && !RedisConfigHelper.getPassword().isEmpty())
                && null != RedisConfigHelper.getTimeout()) {
            jedisPool = new JedisPool(RedisConfigHelper.getJedisPoolConfig(),
                    RedisConfigHelper.getHost(),
                    RedisConfigHelper.getPort(),
                    RedisConfigHelper.getTimeout(),
                    RedisConfigHelper.getPassword());
        }else if ((null == RedisConfigHelper.getPassword() || RedisConfigHelper.getPassword().isEmpty()) && null != RedisConfigHelper.getTimeout()) {
            jedisPool = new JedisPool(RedisConfigHelper.getJedisPoolConfig(),
                    RedisConfigHelper.getHost(),
                    RedisConfigHelper.getPort(),
                    RedisConfigHelper.getTimeout());
        }else{
            jedisPool = new JedisPool(RedisConfigHelper.getJedisPoolConfig(),
                    RedisConfigHelper.getHost(),
                    RedisConfigHelper.getPort());
        }
    }

    private static class SingleHandler{
        private static RedisSinglePool instance = new RedisSinglePool();
    }

    public static RedisSinglePool getInstance(){
        return SingleHandler.instance;
    }

}
